let wx_code = getParam("code")
// let timestamp = Date.now();
// let objstr = "{
// 	"code": '100001',
// 	'message': '服务请求工程',
// 	"data": {
// 		"userld": "1e7f60ccab4a443d8760d9ce5c799e54"
// 	}
// }"
let access_token = "" //访问token/
let ticket = "" //应用ticket
// let nonceStr = 'XKIvykvwOuAeIbl'
// let timestamp = (new Date().valueOf()) / 1000
// let corpid = "ww445f8033443a14aa"
// let signature = ""
let url = "http://zipapp/AIHome/common/index.html"
// let url = "http://zipapp/dome/index.html"

// let vconsole = new VConsole()
$(function () {
	// 隐藏 vConsole 的开关按钮
	$.getScript("./js/jweixin-1.2.0.js", function () {
		//TODO 企信业务内容
	})

	if (wx_code) {
		// alert("wx_code:" + wx_code)
		// $("#output").html(wx_code)
	}
})


function getParam(variable) {
	let query = window.location.search.substring(1);
	let vars = query.split("&");
	for (let i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1]
		}
	}
	return ''
}

//1   获取微信code
function getWxCode() {
	$("#showP").html("正在初始化...")
	//首先判断是否存在
	if (!wx_code) {
		var sURL = sURLgetWxCode;
		sURL += 'appid=' + appid;
		sURL += '&redirect_uri=' + encodeURIComponent(encodeURIComponentUrl);
		sURL += '&response_type=code';
		sURL += '&scope=SCOPE';
		sURL += '&state=STATE';
		sURL += 'agentid=' + magentid;
		sURL += '#wechat_redirect';
		location.href = sURL;
	} else {
		$("#showP").html("初始化失败")
	}
}

//2    通过微信code获取isc_ticket
function getIscToken() {

	$("#showP").html("正在获取TOKEN...")
	var sURL = sURLgetIscToken;
	var param = {
		CODE: wx_code,
		appId: magentid
	}
	param = JSON.stringify(param);
	jQuery.ajax({
		type: "post",
		data: param,
		contentType: "application/json;charset=utf-8",
		url: sURL,
		async: true,
		dataType: "json",
		cache: false,
		success: function (res) {
			// $("#output2").html(json.data.ticket)
			// var storage = window.sessionStorage;
			// storage.setItem('ticket', json.data.ticket);
			// alert("ticket:" + json.data.ticket)
			if (res.data) {
				ticket = res.data.ticket
				if (ticket) {
					if (isFlag) {
						// 开发模式直接跳过
						getAuthentication()
					} else {
						// 生产模式 需要text.js 中的iscp 然后在掉业务
						// 微信注册
						createISCPLink("2021128")
						setTimeout(iscpInit, 3000)

						let dingTime = setInterval(() => {
							if (sessionStorage.getItem("err_msg")) {
								getAuthentication()
								window.clearInterval(dingTime);
							} else {
							}
						}, 500)

					}
				} else {
					$("#showP").html("获取TOKEN失败")
				}
			} else {
				$("#showP").html("获取TOKEN失败！")
			}
		}, error: function (err) {
			$("#showP").html("请求TOKEN失败")
		}
	});
}

// 获取个人信息   请求头
function getAuthentication() {

	$("#showP").html("正在登录...")
	// 加密 每次登录都是新的公钥和私钥  当次登录后的请求从session里获取 session存加密的返回值
	/**
	 * 第一次公钥放进header中
	 * 请求值 data  sm2(str + , + sm3(str))
	 * 
	 * fpuk：前公
	 * fprk：前私
	 * bpuk：后公
	 * bprk：后私
	 * */

	const {publicKey,  privateKey } = sm2.generateKeyPairHex();
	sessionStorage.setItem("fpuk", publicKey)
	sessionStorage.setItem("fprk", privateKey)
	if (sessionStorage.getItem("iscp_port")) {
		iscp_port = sessionStorage.getItem("iscp_port");
	} else {
		iscp_port = ""
	}
	let timestamp = Date.now() + "";
	let pppp = {
		"ticket": ticket,
		"time": timestamp
	}
	pppp = JSON.stringify(pppp)
	let dddd = sm3(pppp)
	$.ajax({
		// url: localUrlLink + iscp_port + "/tjAiAssistant/isc/acceptParam",
		url: localUrlLink + iscp_port + "/yipailu/isc/acceptParam",
		type: "post",
		async: true, //是否同步，false表示同步请求
		dataType: "json",
		// contentType: 'application/x-www-form-urlencoded',
		data: pppp,
		headers: {
			sign: dddd,
			fpuk: publicKey
		},
		success: function (res, txt, xhr) {
			// alert("res " + JSON.stringify(res))
			let Authentication = xhr.getResponseHeader("Authentication")
			let bpuk = xhr.getResponseHeader("bpuk")
			if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
				if (Authentication && bpuk) {
					if (res.code == 200) {
						$("#showP").html("登录成功")
						sessionStorage.setItem("Authentication", Authentication);
						// 用户id
						sessionStorage.setItem("userId", res.resultValue.userId);

						// 邮箱
						sessionStorage.setItem("toMail", res.resultValue.email);
						// 单位id
						sessionStorage.setItem("unitId", res.resultValue.unitId);
						// 后公钥
						sessionStorage.setItem("bpuk", bpuk)
						// 
						// let msgString = fileContent + "," + sm3(fileContent)
						// let newFileContent = sm2.doEncrypt(msgString, sessionStorage.getItem("bpuk"), 0)

						// 用户名
						sessionStorage.setItem("userName", res.resultValue.name);
						// // home导航
						// if (res.resultValue.menus) {
						// 	let NavigationList = JSON.stringify(res.resultValue.menus[1])
						// 	sessionStorage.setItem("NavigationList", NavigationList)
						// 	let functionsifList = JSON.stringify(res.resultValue.menus[2])
						// 	sessionStorage.setItem("functionsifList", functionsifList)
						// 	let ReadilyList = JSON.stringify(res.resultValue.menus[3])
						// 	sessionStorage.setItem("ReadilyList", ReadilyList)
						// }

						let integral = res.resultValue.sumintegral
						let ocrFrequency = res.resultValue.recognition
						let voiceTime = res.resultValue.speech
						let integralRanking = res.resultValue.rowNum //积分排名
						integral = Number(integral)
						sessionStorage.setItem("ocrFrequency", ocrFrequency)
						sessionStorage.setItem("voiceTime", voiceTime)
						sessionStorage.setItem("integral", integral)//初始化存储积分
						sessionStorage.setItem("integralRanking", integralRanking);//积分排名
						// 初始化 积分  总积分integral   ocr已使用次数ocrFrequency 语音已使用时间voiceTime
						let integralTotal = ScoreLevel(integral, ocrFrequency, voiceTime)
						sessionStorage.setItem("integralTotal", JSON.stringify(integralTotal))
						// integralTotal
						// let inteTotal = ScoreLevel(integral, ocrFrequency, voiceTime)
						// sessionStorage.setItem("inteTotal", JSON.stringify(inteTotal))
						let isAgreement = res.resultValue.isAgreement;
						if (sessionStorage.getItem("userId") && sessionStorage.getItem("userName") && sessionStorage.getItem("Authentication") && sessionStorage.getItem("integralTotal")) {
							// addOperator(1, 1, "登录", 1)
							// getDetermine()
							// if (isAgreement == "true") {
								$(location).attr("href", "./common/Home.html");
							// } else {
							// 	$(location).attr("href", "./common/index1.html");
							// }
						}
					} else if (res.code == 500) {
						$("#showP").html("登录失败," + res.resultValueStr)
						mui.toast(res.resultValue, {
							duration: 'long',
							type: 'div'
						})
					} else {
						$("#showP").html("登录失败," + res.resultValueStr)
						mui.toast("请求异常请稍后再试", {
							duration: 'long',
							type: 'div'
						})
					}
				} else {
					$("#showP").html("登录失败," + res.resultValueStr)
					// setTimeout(() => {
					// 	location.reload();
					// }, 1000)
				}

			} else {
				$("#showP").html("登录失败,完整性校验失败！")
				// setTimeout(() => {
				// 	location.reload();
				// }, 1000)
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$("#showP").html("登录请求失败")
		}
		// error: (e) => {
		// 	$("#showP").html("登录请求失败")
		// 	// setTimeout(() => {
		// 	// 	location.reload();
		// 	// }, 1000)
		// },

	});
}

// 查询 是否同意过
// function getDetermine() {
// 	let AuthenticationSession = sessionStorage.getItem("Authentication");
// 	if (sessionStorage.getItem("iscp_port")) {
// 		iscp_port = sessionStorage.getItem("iscp_port");
// 	} else {
// 		iscp_port = ""
// 	}
// 	let pppp = {
// 		// operator: userName,
// 		userId: sessionStorage.getItem("userId"),
// 		operatorType: 4,
// 		operatorBasic: 2,
// 		operatorContent: "同意",
// 		time: timestamp
// 	}
// 	pppp = JSON.stringify(pppp)
// 	let dddd = sm3(pppp)
// 	$.ajax({
// 		type: 'post', // 获取头信息，type=HEAD即可
// 		url: localUrlLink + iscp_port + "/tjAiAssistant/operator/queryUserIsAgree",
// 		headers: {
// 			"Content-Type": "application/json;charset=UTF-8",
// 			sign: dddd,
// 			Authentication: AuthenticationSession
// 		},
// 		async: false, //是否同步，false表示同步请求
// 		dataType: "json",
// 		data: pppp,
// 		success: function (res, txt, xhr) {
// 			if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
// 				let Authentication = xhr.getResponseHeader("Authentication")
// 				if (Authentication) {
// 					sessionStorage.setItem("Authentication", Authentication);
// 					// addOperator(4, 2, "查询同意书", 1)
// 					// alert(res.resultValue)
// 					if (res.resultValue) {
// 						$(location).attr("href", "./common/Home.html");
// 					} else {
// 						$(location).attr("href", "./common/index1.html");
// 					}
// 				}

// 			}
// 		}
// 	});
// }
getWxCode();
getIscToken();